using Dapper;
using Finance.Api.Read.Applications.Commands.库存盘点;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;

namespace Finance.Api.Read.Applications.CommandHands.库存盘点
{
    public class ProductQueryCommandHandlers : IRequestHandler<ProductQueryCommand, ApiResult<ApiPaging<List<ProductDto>>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<ProductQueryCommandHandlers> _logger;

        public ProductQueryCommandHandlers(IDapperDb db, ILogger<ProductQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<List<ProductDto>>>> Handle(ProductQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<List<ProductDto>>>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder totalNum = new StringBuilder();

            ApiPaging<List<ProductDto>> res = new ApiPaging<List<ProductDto>>();
            var parameters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT a.Id,
                            a.ProductNo,
                            a.ProductName,
                            a.ProductNum,
                            a.Location,
                            a.CreateName,
                            a.CreateTime,
                            a.UpdateName,
                            a.UpdateTime,
                            a.DeleteName,
                            a.DeleteTime
                    FROM `Product` a
                    WHERE 1=1
                            AND a.IsDelete=0 ");

                // 产品名称查询条件
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    stringBuilder.Append(" AND a.ProductName LIKE @ProductName ");
                    parameters.Add("ProductName", $"%{request.ProductName}%");
                }

                // 库名查询条件
                if (!string.IsNullOrEmpty(request.Location))
                {
                    stringBuilder.Append(" AND a.Location LIKE @Location ");
                    parameters.Add("Location", $"%{request.Location}%");
                }

                // 产品编号查询条件
                if (!string.IsNullOrEmpty(request.ProductNo))
                {
                    stringBuilder.Append(" AND a.ProductNo LIKE @ProductNo ");
                    parameters.Add("ProductNo", $"%{request.ProductNo}%");
                }

                // 构建总数查询SQL
                totalNum.Append(@"SELECT COUNT(1) FROM `Product` a WHERE 1=1 AND a.IsDelete=0 ");

                // 产品名称查询条件（总数查询）
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    totalNum.Append(" AND a.ProductName LIKE @ProductName ");
                }

                // 库名查询条件（总数查询）
                if (!string.IsNullOrEmpty(request.Location))
                {
                    totalNum.Append(" AND a.Location LIKE @Location ");
                }

                // 产品编号查询条件（总数查询）
                if (!string.IsNullOrEmpty(request.ProductNo))
                {
                    totalNum.Append(" AND a.ProductNo LIKE @ProductNo ");
                }

                // 执行总数查询
                int totalCount = await _db.QueryFirst<int>(totalNum.ToString(), parameters);

                // 添加分页和排序
                stringBuilder.Append($" ORDER BY a.Id DESC LIMIT {((request.index - 1) * request.size)}, {request.size}");

                // 执行数据查询
                var list = await _db.Query<ProductDto>(stringBuilder.ToString(), parameters);
                
                res.data = list.ToList();
                res.totalcount = totalCount;
                res.totalpcount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
                result.data = res;
                result.message = "产品信息分页查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("产品信息分页查询失败: {Message}", ex.Message);
                result.message = "产品信息分页查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 